<template>
  <div class="admin-dashboard">
    <h2>{{ t('admin.dashboard') }}</h2>
    
    <!-- Stats overview -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <h3>{{ stats.totalMerchants }}</h3>
            <p>{{ t('admin.totalMerchants') }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <h3>{{ stats.activeMerchants }}</h3>
            <p>{{ t('admin.activeMerchants') }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <h3>{{ stats.premiumMerchants }}</h3>
            <p>{{ t('admin.premiumMerchants') }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <h3>{{ stats.totalOrders }}</h3>
            <p>{{ t('admin.totalOrders') }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- Charts -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>{{ t('admin.merchantGrowth') }}</span>
          </template>
          <div ref="merchantChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>{{ t('admin.orderStatistics') }}</span>
          </template>
          <div ref="orderChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- Merchant management -->
    <el-card class="merchants-table-card">
      <template #header>
        <div class="card-header">
          <span>{{ t('admin.merchantManagement') }}</span>
          <el-button type="primary" @click="openMerchantForm">{{ t('common.add') }}</el-button>
        </div>
      </template>
      
      <el-table :data="merchants" style="width: 100%">
        <el-table-column prop="id" :label="t('admin.id')" width="80"></el-table-column>
        <el-table-column prop="username" :label="t('admin.username')"></el-table-column>
        <el-table-column prop="businessName" :label="t('admin.businessName')"></el-table-column>
        <el-table-column prop="email" :label="t('admin.email')"></el-table-column>
        <el-table-column :label="t('admin.subscriptionType')">
          <template #default="scope">
            <el-tag 
              :type="scope.row.subscriptionType === 'PREMIUM' ? 'success' : 'warning'" 
              disable-transitions
            >
              {{ t(`admin.subscriptions.${scope.row.subscriptionType.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('admin.status')">
          <template #default="scope">
            <el-tag 
              :type="scope.row.isActive ? 'success' : 'danger'" 
              disable-transitions
            >
              {{ t(`admin.status.${scope.row.isActive ? 'active' : 'inactive'}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('common.actions')">
          <template #default="scope">
            <el-button size="small" @click="editMerchant(scope.row)">{{ t('common.edit') }}</el-button>
            <el-button size="small" type="danger" @click="deleteMerchant(scope.row)">{{ t('common.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Merchant Form Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="merchantForm" :rules="merchantRules" ref="merchantFormRef" label-width="120px">
        <el-form-item :label="t('admin.username')" prop="username">
          <el-input v-model="merchantForm.username"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.email')" prop="email">
          <el-input v-model="merchantForm.email"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.businessName')" prop="businessName">
          <el-input v-model="merchantForm.businessName"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.subscriptionType')" prop="subscriptionType">
          <el-select v-model="merchantForm.subscriptionType">
            <el-option 
              v-for="type in subscriptionTypes" 
              :key="type.value" 
              :label="t(`admin.subscriptions.${type.value.toLowerCase()}`)"
              :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('admin.status')" prop="isActive">
          <el-switch v-model="merchantForm.isActive"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="saveMerchant">{{ t('common.save') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'

export default {
  name: 'AdminDashboard',
  setup() {
    const { t } = useI18n()
    const merchants = ref([])
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const merchantForm = ref({
      id: null,
      username: '',
      email: '',
      businessName: '',
      subscriptionType: 'FREE',
      isActive: true
    })
    const merchantFormRef = ref(null)
    const merchantChart = ref(null)
    const orderChart = ref(null)
    
    const stats = ref({
      totalMerchants: 12,
      activeMerchants: 8,
      premiumMerchants: 4,
      totalOrders: 156
    })
    
    const subscriptionTypes = ref([
      { value: 'FREE', label: 'Free' },
      { value: 'PREMIUM', label: 'Premium' }
    ])
    
    const merchantRules = {
      username: [
        { required: true, message: t('admin.enterUsername'), trigger: 'blur' }
      ],
      email: [
        { required: true, message: t('admin.enterEmail'), trigger: 'blur' },
        { type: 'email', message: t('admin.invalidEmail'), trigger: 'blur' }
      ],
      businessName: [
        { required: true, message: t('admin.enterBusinessName'), trigger: 'blur' }
      ]
    }
    
    const loadMerchants = async () => {
      try {
        // In a real application, you would make an API call to fetch merchants
        // For now, using mock data
        merchants.value = [
          {
            id: 1,
            username: 'merchant1',
            businessName: 'Sample Business 1',
            email: 'merchant1@example.com',
            subscriptionType: 'PREMIUM',
            isActive: true
          },
          {
            id: 2,
            username: 'merchant2',
            businessName: 'Sample Business 2',
            email: 'merchant2@example.com',
            subscriptionType: 'FREE',
            isActive: true
          },
          {
            id: 3,
            username: 'merchant3',
            businessName: 'Sample Business 3',
            email: 'merchant3@example.com',
            subscriptionType: 'FREE',
            isActive: false
          }
        ]
      } catch (error) {
        console.error('Error loading merchants:', error)
      }
    }
    
    const openMerchantForm = () => {
      dialogTitle.value = t('admin.addMerchant')
      merchantForm.value = {
        id: null,
        username: '',
        email: '',
        businessName: '',
        subscriptionType: 'FREE',
        isActive: true
      }
      dialogVisible.value = true
    }
    
    const editMerchant = (merchant) => {
      dialogTitle.value = t('admin.editMerchant')
      merchantForm.value = { ...merchant }
      dialogVisible.value = true
    }
    
    const deleteMerchant = (merchant) => {
      // In a real application, you would make an API call to delete the merchant
      console.log('Delete merchant:', merchant)
      // For now, just show a message
      alert('Merchant deletion would happen here')
    }
    
    const saveMerchant = async () => {
      await merchantFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // In a real application, you would make an API call to save the merchant
            // For now, just show a message
            console.log('Saving merchant:', merchantForm.value)
            dialogVisible.value = false
            
            // Reload merchants
            loadMerchants()
          } catch (error) {
            console.error('Error saving merchant:', error)
          }
        }
      })
    }
    
    const initCharts = () => {
      // Initialize merchant growth chart
      const merchantChartInstance = echarts.init(merchantChart.value)
      merchantChartInstance.setOption({
        title: {
          text: t('admin.merchantGrowth')
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [10, 15, 20, 25, 30, 35],
          type: 'line',
          smooth: true
        }]
      })
      
      // Initialize order statistics chart
      const orderChartInstance = echarts.init(orderChart.value)
      orderChartInstance.setOption({
        title: {
          text: t('admin.orderStatistics')
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [120, 200, 150, 80, 70, 110],
          type: 'bar'
        }]
      })
    }
    
    onMounted(() => {
      loadMerchants()
      initCharts()
    })
    
    return {
      t,
      merchants,
      dialogVisible,
      dialogTitle,
      merchantForm,
      merchantFormRef,
      merchantRules,
      subscriptionTypes,
      stats,
      merchantChart,
      orderChart,
      openMerchantForm,
      editMerchant,
      deleteMerchant,
      saveMerchant
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.charts-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-item h3 {
  margin: 0 0 5px 0;
  font-size: 24px;
  color: #409EFF;
}

.stat-item p {
  margin: 0;
  color: #909399;
}

.merchants-table-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card {
  height: 350px;
}
</style>